const net = require('net')
const request = require('request')

let client = null

const server = net.createServer(socket => {
	socket.on('data', function(raw){
			try{
				raw = raw.toString()
							raw = raw.trim()
				
							console.log(raw)
							
							try{
								let data = JSON.parse(raw) //这是用户请求过来的
								
								client.write(data.data)
								
							}catch(e){ //这是设备请求过来的
								
								
								if(raw === 'register'){
									console.log('register')
									client = socket
								}else{
									
									let data = raw.split(',')
									let status = data[0].split(':')[1]
									let temp = data[1].split(':')[1]
									
									request.post({
												url:'http://127.0.0.1:8080/receive',
												body:JSON.stringify({status : status, temp : temp}),
												timeout : 5000,
												headers:{
													'Content-Type':'application/json'
												}
									})
				
								}
								
								
								
								
								
							}
			}catch(e){

			}
			
				
	})
	
	socket.on('error', function(e){
		console.log(e.message)
	})
	
})

server.listen(7777, () => {
	console.log('server start')
})